import pika


class MqPublisher:

    def __init__(self, url, EXCHANGE, EXCHANGE_TYPE, ROUTING_KEY, QUEUEName):
        self._url = url
        self._EXCHANGE = EXCHANGE
        self._EXCHANGE_TYPE = EXCHANGE_TYPE
        self._ROUTING_KEY = ROUTING_KEY
        self.QUEUENAME = QUEUEName

    def connect(self):
        self._connect = pika.BlockingConnection(pika.URLParameters(self._url))
        self._channel = self._connect.channel()
        self._channel.exchange_declare(exchange=self._EXCHANGE,
                                       exchange_type=self._EXCHANGE_TYPE)
        self._channel.queue_declare(queue=self.QUEUENAME)
        self._channel.queue_bind(exchange=self._EXCHANGE, queue=self.QUEUENAME, routing_key=self._ROUTING_KEY)
        self._channel.confirm_delivery()

    def publasher(self, message, callback,*args,**kwargs):
        if self._connect.is_closed:
            self.connect()
        pika.BasicProperties(
            delivery_mode=2,  # make message persistent
        )
        if self._channel.basic_publish(exchange=self._EXCHANGE,
                                       routing_key=self._ROUTING_KEY,
                                       body=message):
            callback(message,*args,**kwargs)

    def close(self):
        self._connect.close()
